package com.heima.user.service.Impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.UserMapper;
import com.heima.user.service.UserService;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

@Service
public class UserServiceImpl  extends ServiceImpl<UserMapper,ApUser> implements UserService {

    @Override
    public ResponseResult login(LoginDto dto) {
        //判断手机号 密码是否为空
        if(!dto.getPhone().isEmpty()&& dto.getPassword().isEmpty()){
            HashMap<String, String> stringStringHashMap = new HashMap<>();
            String token = AppJwtUtil.getToken(0L);
            stringStringHashMap.put("token",token);
            return  ResponseResult.okResult(stringStringHashMap);
        }
            //判断一下这个手机号是否合法
        String phone = dto.getPhone();
        boolean matches = phone.matches("^1[23456789]\\d{9}$");
        if(!matches){
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //根据手机号获取用户 判断是否存在
        LambdaQueryWrapper<ApUser>  lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ApUser::getPhone,phone);
        ApUser user = this.getOne(lambdaQueryWrapper);
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        //比对一下密码
        String salt = user.getSalt();
        String password = dto.getPassword();

        String s = DigestUtils.md5DigestAsHex((password+salt).getBytes());
        if (!s.equals(user.getPassword())){
            return  ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        user.setSalt(null);
        user.setPassword(null);
        HashMap<String, Object> map = new HashMap<>();
        String token = AppJwtUtil.getToken(user.getId().longValue());

        map.put("date",user);
        map.put("token",token);

        return ResponseResult.okResult(map);
    }
}
